concerto.admin.navMenuEditor = {
	addItem:function(li) {
		var clone = li.clone();
		clone.children('button').remove();
		var text = clone.text();
		$('<li/>').addClass('menu').data('display_name', li.data('display_name')).data('depth', 1).data('resource', li.data('resource')).data('id', li.data('id')).html('<button class="menu-sort-remove">X</button>'
			+ clone.text() + '<button class="menu-sort-move-right">&rarr;</button><button class="menu-sort-move-left">&larr;</button>').appendTo($('#menu-container'));
		this.reorganize();
	},
	render:function(params) {
		for(var i=0;i<params.length;i++) {
			$('<li/>').addClass('menu').data('display_name', params[i].display_name).data('depth', params[i].depth).data('resource', params[i].resource).data('id', params[i].id).html('<button class="menu-sort-remove">X</button>'
			+ params[i].title + '<button class="menu-sort-move-right">&rarr;</button><button class="menu-sort-move-left">&larr;</button>').appendTo($('#menu-container'));
		}
		$('#menu-container').sortable({
			axis:'y',
			stop:function() {
				concerto.admin.navMenuEditor.reorganize();
			}
		});
		$('.menu-sort-remove').live('click', function(e) {
			e.preventDefault();
			$(this).parent('li').remove();
			concerto.admin.navMenuEditor.reorganize();
		});
		$('.menu-sort-move-left').live('click', function(e) {
			e.preventDefault();
			$(this).parent('li').data('depth', $(this).parent('li').data('depth') - 1);
			$(this).parent('li').find('li').each(function() {
				$(this).data('depth', $(this).data('depth') - 1);
			});
			concerto.admin.navMenuEditor.reorganize();
		});
		$('.menu-sort-move-right').live('click', function(e) {
			e.preventDefault();
			$(this).parent('li').data('depth', $(this).parent('li').data('depth') + 1);
			$(this).parent('li').find('li').each(function() {
				$(this).data('depth', $(this).data('depth') + 1);
			});
			concerto.admin.navMenuEditor.reorganize();
		});
		this.reorganize();
	},
	
	reorganize:function() {
		var previous = false;
		$('#menu-container').children('li').each(function() {
			var depth = $(this).data('depth');
			$(this).children('.menu-sort-move-left').hide();
			$(this).children('.menu-sort-move-right').hide();
			$(this).css('margin-left', '0px');
			if(previous) {
				var previousDepth = previous.data('depth');
				if(depth > 1) {
					$(this).children('.menu-sort-move-left').show();
				}
				if(previousDepth >= depth) {
					$(this).children('.menu-sort-move-right').show();
				}
				
				if(depth == previousDepth || Math.abs(depth-previousDepth) == 1) {
					// Difference can only be 1
					$(this).css('margin-left', ((depth-1)*25).toString() + 'px');

				}
				else if(previousDepth < depth) {
					$(this).data('depth', previousDepth + 1);
					$(this).css('margin-left', ((previousDepth)*25).toString() + 'px');
				}
			}
			else {
				$(this).data('depth', 1);
			}	
			previous = $(this);
			
		});
	}
};

